/* eslint-disable react-hooks/exhaustive-deps */
import { Breadcrumb, Button, Card, Form, Input, message, Modal, Radio, Space, Upload } from 'antd'
import Channel from 'Components/Channel'
import React, { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import  styles  from './index.module.scss'
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';
import { getArticlesListAPI, publishArticlesAPI, publishArticlesUrlAPI } from 'api/articles';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { useParams } from 'react-router-dom';
export default function ArticlePublish() {
  const [imgUrl, setImgUrl] = useState('')
  const [fileList, setFileList] = useState([])
  const [type, setType] = useState(1)
  const { id } = useParams()
  const props = {
    name: 'image',
    accept: ".jepg,.jpg,.png",
    action: baseURL + '/v1_0/upload',
    headers: {
      authorization: 'Bearer' + getToken(),
    },
    onChange(info) {
      setFileList(info.fileList)
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onPreview(file) {
      setImgUrl(file.url || file.thumbUrl)
    },

    beforeUpload(file) {
      const whiteList = ['image/jpg', 'image/png', 'image/jpeg']
      if (!whiteList.includes(file.type)) {
        message.warning("文件格式错误")
        return Upload.LIST_IGNORE
      }
    }
  };

  // 存储 点击按钮的type 值
  const handleValuesChange = (changesValues) => {
    if(changesValues.type !== undefined) {
      setType(changesValues.type)
    }
  }

  
  // 定义计算属性
  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false
    if (type === 1) return index === 0
    return true
  })

  const history = useHistory()
  const draftRef = useRef(false)
  const handleSubmitFileList = async (values) => {
    const formData = { ...values }
    formData.cover = {
      type,
      images: type === 0 ? [] : showFileList.map(item => item.url || item.response.data.url)
    }
    delete formData.type
    if (showFileList.length < type) {
      message.warning('图片数量不对')
      return
    }

    if (id) {
      await publishArticlesUrlAPI({ id, ...formData })
      message.success("编辑成功")
    } else {
      await publishArticlesAPI(formData)
      message.success("发布成功")
    }
    history.push("/list")
  }
  
  const formListRef = useRef(null)

  const getArticlesList = async (id) => {
    const res = await getArticlesListAPI(id)
    const type =  res.data.cover.type
    formListRef.current.setFieldsValue({ ...res.data, type })
    setType(type)
    setFileList(res.data.cover.images.map((item) => ({ url: item })))
  }
  useEffect(() => {
    if(id){
    getArticlesList(id)
    }
  }, [])


  return <div style={{ paddingTop: 24 }} className={styles.root}>
    <Card >
      <Breadcrumb>
        <Breadcrumb.Item>
          <Link to={'/hoem'}>首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>{id ? "编辑" : "发布"}文章</Breadcrumb.Item>
      </Breadcrumb>

      <Form ref={formListRef} name="basic" size="large" labelCol={{ span: 4, }} wrapperCol={{ span: 20, }} autoComplete="off" onFinish={handleSubmitFileList} initialValues={{ content: "" }} onValuesChange={handleValuesChange} >
        <Form.Item label="标题" name="title"
          rules={[
            {
              required: true,
              message: '请输入文章标题',
            },
          ]}>
          <Input />
        </Form.Item>

        <Form.Item label="频道" name="channel_id" 
        rules={[
          {
            required: true,
            message: '请选择频道',
          },
        ]}>
          <Channel style={{ width: 200 }}></Channel>
        </Form.Item>

        <Form.Item label="内容" name="content" 
        rules={[
          {
            required: true,
            message: '文章内容不能为空',
          },
          {
            validator: (_, value)=> value==="<p><br></p>" ? Promise.reject(new Error('文章内容不能为空')) : Promise.resolve() 
          },
        ]}>
          <ReactQuill></ReactQuill>
        </Form.Item>

        <Form.Item label="封面" name="type">
          <Radio.Group >
            <Radio value={1}>单图</Radio>
            <Radio value={3}>三图</Radio>
            <Radio value={0}>无图</Radio>
          </Radio.Group>
        </Form.Item>

        {/* JSX 迁移 */}
        <Form.Item wrapperCol={{ offset: 4 }}>
          <Upload {...props} listType="picture-card" fileList={showFileList}>
            {showFileList.length < type && <Button icon={<UploadOutlined />}></Button>}
          </Upload>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 4 }} >
          <Space>
            <Button type="primary" htmlType="submit" >
              {id ? "编辑" : "发布"}文章
            </Button>
            <Button type="primary" htmlType="submit" onClick={() => (draftRef.current = true)}>
              存草稿
            </Button>
          </Space>
        </Form.Item>

      </Form>

      <Modal title="预览图片" visible={!!imgUrl} onCancel={() => setImgUrl("")} footer={null} >
        <img width="400" src={imgUrl} alt="" />
      </Modal>

    </Card>
  </div>
}
